# -*- encoding: utf-8 -*-
"""
File Name: create_all_zabbix_container
Description:
Author : 'lirui'
date: 2024/3/4
Contact: marjey_lee@163.com
Change Activity:
2024/3/4:
"""
import ll
from ll.modules.network.ssh_util.tmp import UbuntuSSHClient
from modules.blk.cmdb.cmdb_service import CMDBService
from projects.generation.create_zabbix_device_snmp_monitor.config.config import UBUNTU_LOGIN_INFO, CONTAINER_MAPPING


def _load_cmdb_container_info():
    data = CMDBService().select('zabbix_docker_info')
    return data['data']['info']


def _get_vm_ssh_clients():
    m = {}
    for ip, login_info in UBUNTU_LOGIN_INFO.items():
        c = UbuntuSSHClient(
            ip=ip,
            username=login_info['username'],
            password=login_info['password']
        )
        m[ip] = c
    return m


def _close_ssh_connection(clients):
    for ip, c in clients.items():
        c.close()


def _create_containers(ssh_clients_mapping):
    for ip, zabbix_ids in CONTAINER_MAPPING.items():
        for zabbix_id in zabbix_ids:
            container_name = f'zabbix-{zabbix_id}'
            ssh = ssh_clients_mapping[ip]
            cmd_lst = [
                f'docker run  -d -it --name {container_name} -p {zabbix_id}:80  -v /etc/localtime:/etc/localtime --restart=unless-stopped my_zabbix_image',
                f'docker exec -it {container_name} bash',
                'service mariadb start ',
                'service  zabbix-server start',
                'service zabbix-agent start',
                'service  apache2 start',
                'exit',
            ]
            for c in cmd_lst:
                ll.get_logger().info(f'execute: {c}')
                res = ssh.run(c)
                ll.get_logger().info(res)


def _main():
    clients_mapping = _get_vm_ssh_clients()
    _create_containers(clients_mapping)
    _close_ssh_connection(clients_mapping)


if __name__ == '__main__':
    _main()
